﻿using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;

namespace CardPlay.Client.Tools
{
    public abstract class Tool : ITool
    {
        private UIElement _captureElement;

        protected Tool(IToolSite site)
        {
            Site = site;
        }

        void ITool.Process(InputEvent inputEvent)
        {
            if (State != null) State(inputEvent);
        }

        protected IToolSite Site
        {
            get;
            private set;
        }

        protected bool IsActivated
        {
            get { return Site.ActiveTool == this; }
            set
            {
                if (value == IsActivated) return;

                if (IsActivated)
                {
                    Site.ActiveTool = null;
                    OnDeactivated();
                }
                else
                {
                    Site.ActiveTool = this;
                    OnActivated();
                }
            }
        }

        protected UIElement CaptureElement
        {
            get { return _captureElement; }
            set
            {
                if (value == CaptureElement) return;

                if (_captureElement != null)
                    _captureElement.ReleaseMouseCapture();

                _captureElement = value;

                if (_captureElement != null)
                {
                    _captureElement.CaptureMouse();

                    var control = _captureElement as Control;
                    if (control != null) control.Focus();
                }
            }
        }

        protected Action<InputEvent> State { get; set; }

        protected virtual void OnActivated()
        {
        }

        protected virtual void OnDeactivated()
        {
        }

        protected virtual bool IsCancelledBy(InputEvent inputEvent)
        {
            switch (inputEvent.Name)
            {
                case InputEvent.LostMouseCapture:
                    return true;

                case InputEvent.KeyDown:
                    return ((KeyEventArgs)inputEvent.Args).Key == Key.Escape;
            }

            return false;
        }
    }
}